const WebSocket = require('ws');

var ws = new WebSocket('wss://ws.coinapi.io/v1/');
ws.on('open', function open() {
  debugger
  var hello = {
    "type": "hello",
    "apikey": "637DDB1B-C7D1-4355-BFD9-4A623C0F142D",
    "heartbeat": false,
    "subscribe_filter_symbol_id":[
      'HUOBIPRO_SPOT_'
    ],
    subscribe_filter_asset_id:[
      'BTC','USDT','ETH'
    ],
    "subscribe_data_type": ["quote","trade"]
  };
  ws.send(JSON.stringify(hello));
});
Date.prototype.addHours = function(h) {    
  this.setTime(this.getTime() + (h*60*60*1000)); 
  return this;   
}
module.exports=function wsService(app) {
  app.globalData.quote = {}
  let quoteArray = [],tradeArray = [],i = 0,j=0;
  ws.on('message', function incoming(data) {
    debugger
    const obj = JSON.parse(data);
    if(obj.type === 'quote') {
      obj.time_exchange = new Date(obj.time_exchange).addHours(8)
      quoteArray.push(obj)
      app.globalData.quote[obj.symbol_id] = obj
      i++;
      if(i=== 100) {
        try {
          app.service('quote')
          .create(quoteArray)
          i=0;
          quoteArray = [];
        } catch(e) {
          console.log(e)
        }
      }
    }
    if(obj.type === 'trade') {
      obj.time_exchange = new Date(obj.time_exchange).addHours(8)
      obj.time_coinapi = new Date(obj.time_coinapi).addHours(8)
      tradeArray.push(obj)
      j++;
      if(j=== 10) {
        try {
          app.service('trade')
          .create(tradeArray)
          j=0;
          tradeArray = [];
        } catch(e) {
          console.log(e)
        }
      }
    }
  });
}

